package com.lqq.chapter05;

import java.util.concurrent.TimeUnit;

/**
 * @Author lqq677
 * @Date 2021/8/11 12:02
 * @Description 死锁
 */
public class DeadLock {
    private static String A = "锁A";
    private static String B = "锁B";

    public static void main(String[] args) {

        //线程A，持有锁A获取锁B
        new Thread(() ->{

            synchronized (A) {
                System.out.println(Thread.currentThread().getName()+"持有锁A，试图获取锁B...");

                //为了效果明显，阻塞1秒
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                synchronized (B) {
                    System.out.println(Thread.currentThread().getName() + "获取到锁B");
                }
            }

                }, "线程A").start();

        //线程B，持有锁B获取锁A
        new Thread(() ->{

            synchronized (B) {
                System.out.println(Thread.currentThread().getName()+"持有锁B，试图获取锁A...");

                //为了效果明显，阻塞1秒
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                synchronized (A) {
                    System.out.println(Thread.currentThread().getName() + "获取到锁A");
                }
            }

        }, "线程B").start();
    }
}
